package com.example.music.Controller;

import com.example.music.model.User;
import com.example.music.service.UserService;
import com.example.music.tool.Constant;
import com.example.music.tool.ResponMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController()
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
//登录功能（未加密）
    @RequestMapping("/login")
    public ResponMessage<User> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        User userinfo = userService.login(user);
        if (userinfo != null) {
            System.out.println("success");
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponMessage<>(1, "success", userinfo);
        } else {
            System.out.println("lose");
            return new ResponMessage<>(-1, "lose", userinfo);

        }
    }
//登录功能（已加密）
@Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login1")
    public ResponMessage<User> login1(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
        User user = new User();
        user.setUsername(username);
        User userinfo = userService.login1(user);
        if (userinfo == null) {
            System.out.println("lose");
            return new ResponMessage<>(-1, "lose", userinfo);

        } else {
            if (!bCryptPasswordEncoder.matches(password, userinfo.getPassword())) {
                return new ResponMessage<>(-1, "⽤⼾名或者密码错误", userinfo);
            }
                System.out.println("success");
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
                return new ResponMessage<>(0, "success", userinfo);

            }
        }
        //获取会话存的内容
        @RequestMapping("/session")
    void session(HttpSession httpSession){
      User user= (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
            System.out.println(user);
        }

    }

